package com.etong.citymap.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.etong.citymap.bean.ImageBean;
import com.etong.citymap.bean.ScreenBean;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.ActivityUtil;
import com.etong.citymap.util.ImageTools;
import com.etong.citymap.util.Status;

/**
 * 请选择上传的图片 拍照、确定
 */
public class CamerDisplayActivity extends Activity {
	LinearLayout list_t0;
	LinearLayout list_t1;
	ArrayList<String> imagelistpath;
	AlertDialog loadingdialog;
	Button camerdisplay_back;
	private ArrayList<ImageView> selectview;
	ScreenBean screenBean;
	LinearLayout canerdisp_t2;
	LinearLayout canerdisp_t1;
	boolean t1 = false;
	boolean t2 = false;
	boolean t3 = false;
	boolean first = true;

	private String currentPath;	//当前拍照文件 一次只能拍一张
	String path = "";
	private Vibrator vibrator;
	boolean iszhidu;// 只读
	private CityApplication cityApplication;
	Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 3) {
				list_t0.removeAllViews();
				selectview.clear();
				if (cityApplication.getImageList() != null) {
					View view = null;
					ImageView m1 = null;
					ImageView m2 = null;
					for (int i = 1; i <= cityApplication.getImageList().length; i++) {
						if (i % 2 == 0) {
							m2.setImageBitmap(cityApplication.getImageList()[i - 1].getBitmap());
							m2.setOnClickListener(clickListener);
							if (!iszhidu) {
								m2.setOnLongClickListener(onLongClickListener);
							}
							m2.setTag((i - 1));
							ImageView select_t2 = (ImageView) view.findViewById(R.id.image_t2_select);
							select_t2.setImageResource(R.drawable.camerselect);
							selectview.add(select_t2);
							list_t0.addView(view);
						} else {
							view = LayoutInflater.from(CamerDisplayActivity.this).inflate(R.layout.imageitem, null);
							m1 = (ImageView) view.findViewById(R.id.image_t1);
							m2 = (ImageView) view.findViewById(R.id.image_t2);
							m1.setTag((i - 1));
							ImageView select_t1 = (ImageView) view.findViewById(R.id.image_t1_select);
							select_t1.setImageResource(R.drawable.camerselect);
							selectview.add(select_t1);
							m1.setOnClickListener(clickListener);
							if (!iszhidu) {
								m1.setOnLongClickListener(onLongClickListener);
							}
							m1.setImageBitmap(cityApplication.getImageList()[i - 1].getBitmap());
						}
					}
					if (cityApplication.getImageList().length % 2 != 0) {
						list_t0.addView(view);
					}
				}
				if (first && cityApplication.getImageList_Net() != null) {
					View view = null;
					ImageView m1 = null;
					ImageView m2 = null;
					int j=1;
					for (int i = 1; i <= cityApplication.getImageList_Net().length; i++) {
						if (cityApplication.getImageList_Net()[i - 1].getType() == Status.ProjectType_SB) {
							if (!t1) {

								if(view!=null) {
									list_t1.addView(view);
									j=1;
								}
								View headerview=LayoutInflater.from(CamerDisplayActivity.this).inflate(R.layout.fengexian, null);
								TextView textView = (TextView) headerview.findViewById(R.id.fengex_title);
								textView.setText("案件上报图片");
								list_t1.addView(headerview);
								t1 = true;
							}

						}
						if (cityApplication.getImageList_Net()[i - 1].getType() == Status.ProjectType_HC) {
							if (!t2) {
								if(view!=null) {
									list_t1.addView(view);
									j=1;
								}
								View headerview=LayoutInflater.from(CamerDisplayActivity.this).inflate(R.layout.fengexian, null);
								TextView textView = (TextView) headerview.findViewById(R.id.fengex_title);
								textView.setText("案件处置图片");
								list_t1.addView(headerview);
								t2 = true;
							}
						}
						if (cityApplication.getImageList_Net()[i - 1].getType() == Status.ProjectType_HS) {
							if (!t3) {
								if(view!=null) {
									list_t1.addView(view);
									j=1;
								}
								View headerview=LayoutInflater.from(CamerDisplayActivity.this).inflate(R.layout.fengexian, null);
								TextView textView = (TextView) headerview.findViewById(R.id.fengex_title);
								textView.setText("案件核实图片");
								list_t1.addView(headerview);
								t3 = true;
							}

						}
						if (j ==2) {
							m2.setImageBitmap(cityApplication.getImageList_Net()[i - 1].getBitmap());
							m2.setOnClickListener(clickListener1);
							m2.setTag((i - 1));
							ImageView select_t2 = (ImageView) view
									.findViewById(R.id.image_t2_select);
							selectview.add(select_t2);
							list_t1.addView(view);
							j=1;
							view=null;
						} else {
							view = LayoutInflater.from(CamerDisplayActivity.this).inflate(R.layout.imageitem, null);
							m1 = (ImageView) view.findViewById(R.id.image_t1);
							m2 = (ImageView) view.findViewById(R.id.image_t2);
							m1.setTag((i - 1));
							ImageView select_t1 = (ImageView) view
									.findViewById(R.id.image_t1_select);
							selectview.add(select_t1);
							m1.setOnClickListener(clickListener1);
							m1.setImageBitmap(cityApplication.getImageList_Net()[i - 1].getBitmap());
							j=2;
						}

					}
					if(j==2)
						list_t1.addView(view);
					first = false;
				}

				loadingdialog.dismiss();
			}
			return false;
		}
	});
	protected String currentFilename;
	private Button button1;
	private Button button2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camerdisplay);
		cityApplication = (CityApplication)getApplication();
		path=Environment.getExternalStorageDirectory()+ cityApplication.CameraPath;
		Intent intent = this.getIntent();
		imagelistpath = intent.getStringArrayListExtra("list");
		iszhidu = intent.getBooleanExtra("iszhidu", false);
		screenBean = ActivityUtil.getScreenWidthAndHeight(this);
		init();
		if ((imagelistpath != null) || (cityApplication.getImageList() != null)) {
			canerdisp_t1show();
		} else {
			canerdisp_t2show();
		}
		if (cityApplication.getImageList_Net() == null) {
			canerdisp_t1.setVisibility(LinearLayout.GONE);
			canerdisp_t2.setVisibility(LinearLayout.GONE);
		}
		selectview = new ArrayList<ImageView>();
		// android 7.0系统解决拍照的问题
		StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
		StrictMode.setVmPolicy(builder.build());
		builder.detectFileUriExposure();
		//new Loading(1);

	}

	void init() {
		list_t0 = (LinearLayout) findViewById(R.id.camer_display_list);
		list_t1 = (LinearLayout) findViewById(R.id.camer_display_list_t1);
		button2 = (Button) findViewById(R.id.button2);
		camerdisplay_back = (Button) findViewById(R.id.camerdisplay_back);
		button2.setOnClickListener(onClickListener);
		camerdisplay_back.setOnClickListener(onClickListener);
		canerdisp_t1 = (LinearLayout) findViewById(R.id.canerdisp_t1);
		canerdisp_t2 = (LinearLayout) findViewById(R.id.canerdisp_t2);
		canerdisp_t1.setOnClickListener(onClickListener);
		canerdisp_t2.setOnClickListener(onClickListener);
		button1 = (Button)findViewById(R.id.button1);
		button1.setOnClickListener(onClickListener);
	}

	class Loading extends Thread {
		private int type;
		public Loading(int type) {
			this.type = type;
			start();
		}

		@Override
		public void run() {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;
			if (type==1 && imagelistpath != null) {
				ImageBean ibs[] = null;
				int len = 0;
				ImageBean[] cache = null;
				if (cityApplication.getImageList() == null) {
					ibs = new ImageBean[imagelistpath.size()];
					//cityApplication.setImageList();
					//ImageList = new ImageBean[imagelistpath.size()];
				} else {
					cache = new ImageBean[cityApplication.getImageList().length];
					for (int i = 0; i < cache.length; i++) {
						cache[i] = new ImageBean();
						ImageBean cachebean = cityApplication.getImageList()[i];
						cache[i].setBitmap(cachebean.getBitmap());
						cache[i].setIsSelect(cachebean.isIsSelect());
						cache[i].setPathname(cachebean.getPathname());
						cache[i].setTag(cachebean.getTag());
						cache[i].setUrlpath(cachebean.getUrlpath());
					}
					len = cache.length;
					ibs = new ImageBean[len + imagelistpath.size()];
					//ImageList = new ImageBean[len + imagelistpath.size()];
					for (int i = 0; i < cache.length; i++) {
						ibs[i] = new ImageBean();
						ibs[i].setBitmap(cache[i].getBitmap());
						ibs[i].setIsSelect(cache[i].isIsSelect());
						ibs[i].setPathname(cache[i].getPathname());
						ibs[i].setTag(cache[i].getTag());
						ibs[i].setUrlpath(cache[i].getUrlpath());
					}
					//cityApplication.setImageList(ibs);
				}

				for (int i = (len); i < (imagelistpath.size() + len); i++) {
					ibs[i] = new ImageBean();
					Bitmap bitmap = BitmapFactory.decodeFile(path + "/"+ imagelistpath.get(i - len));
					ibs[i].setBitmap(bitmap);
					ibs[i].setIsSelect(true);
					ibs[i].setPathname(imagelistpath.get(i - len));
					ibs[i].setTag(i + "");
				}
				if(imagelistpath!=null) imagelistpath.clear();
				cityApplication.setImageList(ibs);
			}
			if (first && type==2 && cityApplication.getImageList_Net() != null) {
				for (int i = 0; i < cityApplication.getImageList_Net().length; i++) {
					if(cityApplication.getImageList_Net()[i].getBitmap()==null){
						Bitmap bitmap = HttpSendData.returnBitMap(cityApplication.getImageList_Net()[i].getUrlpath());
						cityApplication.getImageList_Net()[i].setBitmap(bitmap);
					}
				}
			}
			handler.sendEmptyMessage(3);
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private OnClickListener onClickListener = new OnClickListener() {


		@Override
		public void onClick(View v) {
			if (button2 == v || camerdisplay_back == v) {
				if (cityApplication.getImageList() != null) {
					ArrayList<ImageBean> beans = new ArrayList<ImageBean>();
					for (int i = 0; i < cityApplication.getImageList().length; i++) {
						if (cityApplication.getImageList()[i].isIsSelect()) {
							beans.add(cityApplication.getImageList()[i]);
						} else {
							File file = new File(path + "/"	+ cityApplication.getImageList()[i].getPathname());
							if (file.exists()) {
								file.delete();
							}
						}
					}
					cityApplication.setImageList(new ImageBean[beans.size()]);
					//ImageList = new ImageBean[beans.size()];
					for (int i = 0; i < beans.size(); i++) {
						ImageBean cache = beans.get(i);
						cityApplication.getImageList()[i] = new ImageBean();
						cityApplication.getImageList()[i].setBitmap(cache.getBitmap());
						cityApplication.getImageList()[i].setIsSelect(cache.isIsSelect());
						cityApplication.getImageList()[i].setPathname(cache.getPathname());
						cityApplication.getImageList()[i].setTag(i + "");
						cityApplication.getImageList()[i].setUrlpath(cache.getUrlpath());
					}

				}
				finish();
			} else if ( button1 == v) {
				if(imagelistpath!=null) {
					imagelistpath.clear();
				}else{
					imagelistpath = new ArrayList<String>();
				}
				Intent intent = new Intent();
				// 指定开启系统相机的Action
				intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				// 根据文件地址创建文件
				Date date = new Date();
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
				currentPath = Environment.getExternalStorageDirectory()+ cityApplication.CameraPath;
				currentFilename = format.format(date) + ".jpg";
				File fileFolder = new File(currentPath);
				if (!fileFolder.exists()) {
					fileFolder.mkdir();
				}
				File file = new File(currentPath+"/"+currentFilename);
				if (file.exists()) {
					file.delete();
				}
				// 把文件地址转换成Uri格式
				Uri uri = Uri.fromFile(file);
				// 设置系统相机拍摄照片完成后图片文件的存放地址
				intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				startActivityForResult(intent, 0);
			} else if (canerdisp_t2 == v) {
				canerdisp_t2show();
			} else if (canerdisp_t1 == v) {
				canerdisp_t1show();
			}
		}
	};

	void canerdisp_t1show() {
		canerdisp_t1.setBackgroundResource(R.drawable.mytypeback_down);
		canerdisp_t2.setBackgroundResource(R.drawable.mytypeback);
		list_t1.setVisibility(LinearLayout.GONE);
		list_t0.setVisibility(LinearLayout.VISIBLE);
		loadingdialog = new ProgressDialog(this);
		loadingdialog.setTitle(null);
		loadingdialog.setMessage("请稍等,数据加载中...");
		loadingdialog.setCanceledOnTouchOutside(false);
		loadingdialog.show();

		new Loading(1);
	}

	void canerdisp_t2show() {
		canerdisp_t2.setBackgroundResource(R.drawable.mytypeback_down);
		canerdisp_t1.setBackgroundResource(R.drawable.mytypeback);
		list_t0.setVisibility(LinearLayout.GONE);
		list_t1.setVisibility(LinearLayout.VISIBLE);
		if(first){
			loadingdialog = new ProgressDialog(this);
			loadingdialog.setTitle(null);
			loadingdialog.setMessage("请稍等,数据加载中...");
			loadingdialog.setCanceledOnTouchOutside(false);
			loadingdialog.show();
			new Loading(2);
		}
	}

	public OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			cityApplication.setImageListPosttion(0);
			//ImageListPosttion = 0;
			ImageView imageView = ((ImageView) v);
			int tag = (Integer) imageView.getTag();
			Intent intent = new Intent(CamerDisplayActivity.this,
					CameraDisplayGalleryActivity.class);
			intent.putExtra("selectpotion", tag);
			startActivity(intent);
		}
	};

	public OnClickListener clickListener1 = new OnClickListener() {

		@Override
		public void onClick(View v) {
			cityApplication.setImageListPosttion(1);
			//ImageListPosttion = 1;
			ImageView imageView = ((ImageView) v);
			int tag = (Integer) imageView.getTag();
			Intent intent = new Intent(CamerDisplayActivity.this,
					CameraDisplayGalleryActivity.class);
			intent.putExtra("selectpotion", tag);
			startActivity(intent);
		}
	};
	private OnLongClickListener onLongClickListener = new OnLongClickListener() {
		@Override
		public boolean onLongClick(View v) {
			ImageView imageView = ((ImageView) v);
			int tag = (Integer) imageView.getTag();
			ImageView selectcacheview = selectview.get(tag);
			if (cityApplication.getImageList()[tag].isIsSelect()) {
				cityApplication.getImageList()[tag].setIsSelect(false);
				selectcacheview.setImageResource(0);
			} else {
				selectcacheview.setImageResource(R.drawable.camerselect);
				cityApplication.getImageList()[tag].setIsSelect(true);
			}
			zhendong();
			return true;
		}
	};

	public void zhendong() {
		if (vibrator == null) {
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		}
		long[] pattern = { 100, 400 }; // 停止 开启 停止 开启
		vibrator.vibrate(pattern, 1);
	}

	@Override
	public void onStop() {
		super.onStop();
		if (vibrator != null) {
			vibrator.cancel();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*ImageBean imagebean = new ImageBean();
		Bitmap bitmap = BitmapFactory.decodeFile(currentPath);
		imagebean.setBitmap(bitmap);
		imagebean.setIsSelect(true);
		imagebean.setPathname(currentFilename);
		imagebean.setTag(UUID.randomUUID().toString());*/
		if (resultCode == RESULT_OK) {
			//将保存在本地的图片取出并缩小后显示在界面上  
			Bitmap bitmap = ImageTools.loadBitmap(currentPath+"/"+currentFilename, true);//BitmapFactory.decodeFile(currentPath+"/"+currentFilename); 
			Bitmap newBitmap = bitmap;
			if(bitmap.getWidth()>=bitmap.getHeight() && bitmap.getWidth()>1024){
				int h = 1024*bitmap.getHeight()/bitmap.getWidth();
				newBitmap = ImageTools.zoomBitmap(bitmap, 1024, h);  
				bitmap.recycle();  
			}else if(bitmap.getWidth()<bitmap.getHeight() && bitmap.getHeight()>1024){
				int w = 1024*bitmap.getWidth()/bitmap.getHeight();
				newBitmap = ImageTools.zoomBitmap(bitmap, w, 1024);  
				bitmap.recycle();  
			}
			//由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常  
			File f = new File(currentPath+"/"+currentFilename);
			if(f.exists()) f.delete();
			//将处理过的图片显示在界面上，并保存到本地  
			ImageTools.savePhotoToSDCard(newBitmap, currentPath+"/"+currentFilename, Bitmap.CompressFormat.JPEG);  
			newBitmap.recycle();  
			imagelistpath.add(currentFilename);
			canerdisp_t1show();
		}
	}
}
